package com.acme.javaschool.sems.ionio.filetools;

import java.io.*;

import static java.lang.StrictMath.min;

public class IoTools {
    public static boolean v = true; //verbose

    public static boolean copyIo(String fromPath, String toPath) {

        try (FileInputStream in = new FileInputStream(fromPath);
             FileOutputStream out = new FileOutputStream(toPath);
        ) {

            byte[] readBytes = new byte[in.available()];
            int bytesRead = in.read(readBytes);
            out.write(readBytes);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    public static int transferChunkIo(InputStream from, OutputStream to, int chunkSize) throws IOException {
        byte[] readBytes = new byte[min(chunkSize, from.available())];

        int bytesRead = from.read(readBytes);
        to.write(readBytes);

        return bytesRead;
    }

    public static boolean compareFilesIo(String pathA, String pathB) {
        try (FileInputStream ina = new FileInputStream(pathA);
             FileInputStream inb = new FileInputStream(pathB);
        ) {
            if (v) { System.out.println("[compareIo] started"); }

            byte[] readBytesa = new byte[ina.available()];
            byte[] readBytesb = new byte[inb.available()];
            ina.read(readBytesa);
            inb.read(readBytesb);

            System.out.println(readBytesa.length);
            System.out.println(readBytesb.length);
            for (int i = 0; i < min(readBytesa.length, readBytesb.length); i++) {
                if (readBytesa[i] != readBytesb[i]) {
                    System.out.println(i);
                    return false;
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        if (v) { System.out.println("[compareIo] done."); }
        return true;
    }

}
